package com.zink.ezequiel.codes;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;
import android.widget.AdapterView.OnItemSelectedListener;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.desandroid.framework.ada.Entity;
import com.desandroid.framework.ada.exceptions.AdaFrameworkException;
import com.zink.ezequiel.codes.data.ApplicationDataContext;
import com.zink.ezequiel.codes.data.model.Entry;
import com.zink.ezequiel.codes.data.model.Tag;

@SuppressLint("NewApi")
public class CodeDetailsActivity extends SherlockActivity implements OnItemSelectedListener {

    private static final String TAG = "CodeActivity";
    public static final String PARCEL_ENTRY_ID = "com.zink.ezequiel.codes.parcel.entry.id";
    public static final String PARCEL_ENTRY_MODE = "com.zink.ezequiel.codes.parcel.entry.mode";
	public static final long EDIT_MODE = 1;
	public static final long VIEW_MODE = 2;
	public static final long NEW_MODE = 3;
	
	boolean entryChanged;

    private ApplicationDataContext dataContext;

    private Entry entry;
    
    private ArrayAdapter<Tag> tagListAdapter;
    
    private long mode;
    
    AlertDialog promptTag;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    	Long mode;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_code_details);
        try {
            dataContext = new ApplicationDataContext(this);

            Bundle b = getIntent().getExtras();
	    	loadTagSpinner();
            if (b != null){
            	if (b.containsKey(PARCEL_ENTRY_MODE)) {
            		//Retrieving param
            		mode = b.getLong(PARCEL_ENTRY_MODE);
            		switchUIMode(mode);
            	} else {
            		entry = new Entry();
            	}
            	
            	if (b.containsKey(PARCEL_ENTRY_ID)) {
            		//Retrieving param
            		long entryID = b.getLong(PARCEL_ENTRY_ID);
            		loadInformation(entryID);
            	}
            } else {
        		entry = new Entry();
        		switchUIMode(NEW_MODE);
        	}
        } catch (Exception e) {
            Log.e(TAG, "Exception was caught creating ApplicationDataContext", e);
            Toast.makeText(this, "Error loading Entry information", Toast.LENGTH_SHORT).show();
            entry = new Entry();
			switchUIMode(NEW_MODE);
        }
        
        ImageButton newTagButton = (ImageButton) findViewById(R.id.newTagButton);
        newTagButton.setOnClickListener(new View.OnClickListener() {
        	public void onClick(View v) {
        		promptTag.show();
            }
        });
        createPromptDialog();
    }

    private void createPromptDialog() {
		promptTag = new AlertDialog.Builder(this).create();
		promptTag.setTitle("New Tag");
		promptTag.setMessage("Please, enter a tag name");
		// Set an EditText view to get user input 
		final EditText input = new EditText(this);
		promptTag.setView(input);

		promptTag.setButton("OK", new DialogInterface.OnClickListener() {
		   public void onClick(DialogInterface dialog, int which) {
		      String value = input.getText().toString();
		      Tag tag = new Tag(value);
		      dataContext.getTagsSet().add(tag);
		      
		      try {
				dataContext.getTagsSet().save();
			} catch (AdaFrameworkException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		      entry.setTag(dataContext.getTagsSet().get(dataContext.getTagsSet().size()-1));
		      setSpinnerFromTag(dataContext.getTagsSet().get(dataContext.getTagsSet().size()-1));
		   }
		});
	}

	private void switchUIMode(long mode) {
		boolean enabled = (mode == EDIT_MODE) || (mode == NEW_MODE);
		if (this.mode != mode) {
			this.mode = mode;
			//Invalidate menu
			this.invalidateOptionsMenu();
		} else {
			this.mode = mode;
		}

		EditText edit = (EditText) findViewById(R.id.entryName);
    	edit.setEnabled(enabled);

    	edit = (EditText) findViewById(R.id.entryURL);
    	edit.setEnabled(enabled);
    
    	edit = (EditText) findViewById(R.id.editUserName);
    	edit.setEnabled(enabled);
    
    	edit = (EditText) findViewById(R.id.editUserPassword);
    	edit.setEnabled(enabled);
    
    	edit = (EditText) findViewById(R.id.editEntryNotes);
    	edit.setEnabled(enabled);

	    edit = (EditText) findViewById(R.id.editEntryTagText);
	    edit.setEnabled(enabled);
    	
    	Spinner spinner = (Spinner) findViewById(R.id.editEntryTagSpinner);
    	ImageButton newTagButton = (ImageButton) findViewById(R.id.newTagButton);
		if(enabled) {
			edit = (EditText) findViewById(R.id.editEntryTagText);
	    	edit.setVisibility(View.GONE);
	    	spinner.setVisibility(View.VISIBLE);
	    	newTagButton.setVisibility(View.VISIBLE);
			entryChanged = true;
		} else {
			spinner.setVisibility(View.GONE);
	    	newTagButton.setVisibility(View.GONE);

			edit.setVisibility(View.VISIBLE);
			entryChanged = false;
		}   	
    }
    
    private void loadTagSpinner() {
        Spinner spinner = (Spinner) findViewById(R.id.editEntryTagSpinner);
        tagListAdapter = new ArrayAdapter<Tag>(this, android.R.layout.simple_spinner_item);
        
        // Specify the layout to use when the list of choices appears
        tagListAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        try {
            dataContext.getTagsSet().fill();
        } catch (AdaFrameworkException e) {
            Log.e(TAG, "Exception was caught creating ApplicationDataContext", e);
            Toast.makeText(this, "Error loading Tags list", Toast.LENGTH_SHORT).show();
        }
        spinner.setAdapter(tagListAdapter);
        dataContext.getTagsSet().setAdapter(tagListAdapter);

        spinner.setOnItemSelectedListener(this);

	}

	@Override 
    public void onBackPressed() {
    	if ((entryChanged) && ((this.mode == NEW_MODE) || (this.mode == EDIT_MODE))) {
    		AlertDialog.Builder builder = new AlertDialog.Builder(this);

    		builder.setMessage(R.string.dialog_save_message)
    		       .setTitle(R.string.dialog_save_title);
    		builder.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	        	   	onMenuSave();
    	        	   	CodeDetailsActivity.super.onBackPressed();
    	           }
    	       });
    		builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface arg0, int arg1) {
					CodeDetailsActivity.super.onBackPressed();
				}
    	       });
    		AlertDialog dialog = builder.create();
    		dialog.show();
    	} else {
    		super.onBackPressed();
    	}
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = this.getSupportMenuInflater();
        inflater.inflate(R.menu.activity_code_details, menu);
        if(mode == NEW_MODE) {
        	menu.findItem(R.id.menu_edit).setVisible(false);
        	menu.findItem(R.id.menu_update).setVisible(false);
        	menu.findItem(R.id.menu_new).setVisible(false);
        } else if(mode == EDIT_MODE) {
        	menu.findItem(R.id.menu_edit).setVisible(false);
        	menu.findItem(R.id.menu_save).setVisible(false);
        } else {
        	menu.findItem(R.id.menu_update).setVisible(false);
        	menu.findItem(R.id.menu_save).setVisible(false);
        }
        menu.findItem(R.id.menu_edit);
        return true;
    }
    

    private void loadInformation(long songID) throws AdaFrameworkException {

	    this.entry = dataContext.getEntriesSet().getElementByID(songID);
	
	    EditText edit = (EditText) findViewById(R.id.entryName);
	    edit.setText(entry.getEntryName());
	
	    edit = (EditText) findViewById(R.id.entryName);
	    edit.setText(entry.getEntryName());
	
	    edit = (EditText) findViewById(R.id.entryURL);
	    edit.setText(entry.getUrl());
	    
	    edit = (EditText) findViewById(R.id.editUserName);
	    edit.setText(entry.getUserName());
	    
	    edit = (EditText) findViewById(R.id.editUserPassword);
	    edit.setText(entry.getUserPassword());
	    
	    edit = (EditText) findViewById(R.id.editEntryNotes);
	    edit.setText(entry.getNote());
	    
	    edit = (EditText) findViewById(R.id.editEntryTagText);
	    edit.setText(entry.getTag().getTagName());
	    setSpinnerFromTag(entry.getTag());
    }
    
    private void setSpinnerFromTag(Tag tag) {
		int pos = dataContext.getTagsSet().indexOf(tag);
		if (pos != -1) {
	    	Spinner spinner = (Spinner) findViewById(R.id.editEntryTagSpinner);
	    	spinner.setSelection(pos);
		}
	}

	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.menu_new:
            	onMenuNew();
                return true;
            case R.id.menu_edit:
            	onMenuEdit();
            	return true;
            case R.id.menu_lock:
            	onMenuLock();
                return true;
            case R.id.menu_save:
            	onMenuSave();
                return true;
            case R.id.menu_update:
            	onMenuSave();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    private void onMenuNew() {
        Toast.makeText(this, "New option clicked", Toast.LENGTH_SHORT).show();
    }

    private void onMenuEdit() {
    	switchUIMode(EDIT_MODE);
    }
    
    private void onMenuSave() {
        try {
        	
             entry.setEntryName(((EditText) findViewById(R.id.entryName)).getText().toString());
             entry.setNote(((EditText) findViewById(R.id.editEntryNotes)).getText().toString());
             entry.setUrl(((EditText) findViewById(R.id.entryURL)).getText().toString());
             entry.setUserName(((EditText) findViewById(R.id.editUserName)).getText().toString());
             entry.setUserPassword(((EditText) findViewById(R.id.editUserPassword)).getText().toString());
            // Cheking if we are creating a new entry.
            if (entry.getID() != null && entry.getID() != 0) {
            	entry.setStatus(Entity.STATUS_UPDATED);
            }

            dataContext.getEntriesSet().save(this.entry);
            Toast.makeText(this, "Entry updated!", Toast.LENGTH_SHORT).show();
            entryChanged = false;
        } catch (Exception e) {
            Log.e(TAG, "Exception was caught creating ApplicationDataContext", e);
            Toast.makeText(this, "Error loading entry list", Toast.LENGTH_SHORT).show();
        }
    }

    private void onMenuLock() {
    	Toast.makeText(this, "Lock option clicked", Toast.LENGTH_SHORT).show();
    }

    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
    	// TODO Auto-generated method stub
    	Tag tag = dataContext.getTagsSet().get(pos);
    	entry.setTag(tag);
    }

	public void onNothingSelected(AdapterView<?> parent) {
		// TODO Auto-generated method stub
		
	}

}